package com.wsoft.manager;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.service.RedisService;
import com.wsoft.entity.TsCodeRulesEntity;
import com.wsoft.mapper.TsCodeRulesMapper;
import com.wsoft.query.rules.CodeRulesListQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author z001
 * @Date 2024/10/16 13:24
 */
@Service
public class TsCodeRulesManager extends ServiceImpl<TsCodeRulesMapper, TsCodeRulesEntity> {

    @Resource
    private RedisService redisService;

    /**
     * 根据code查询
     * @param code
     * @return
     */
    @GetRedisCache( type = RedisKeyConstant.Rule.RULE_CODE,
            value = RedisKeyConstant.REDIS_SELF)
    public TsCodeRulesEntity getByCode(String code){
        if (StrUtil.isBlank(code)) {
            return null;
        }
        QueryWrapper<TsCodeRulesEntity> query = new QueryWrapper<>();
        query.lambda().eq(TsCodeRulesEntity::getCode,code);
        return getOne(query);
    }

    /**
     * 修改
     * @param entity
     * @return
     */
    @Override
    public boolean updateById(TsCodeRulesEntity entity){
        boolean b = super.updateById(entity);
        if(b){
            redisService.del(RedisKeyConstant.Rule.RULE_CODE + entity.getCode());
            redisService.del(RedisKeyConstant.Rule.RULE_ID + entity.getId());
        }
        return b;
    }

    /**
     * 移除
     * @param id
     * @return
     */
    public boolean removeById(Long id) {
        TsCodeRulesEntity entity = this.getById(id);
        boolean b = super.removeById(id);
        if(b){
            redisService.del(RedisKeyConstant.Rule.RULE_CODE + entity.getCode());
            redisService.del(RedisKeyConstant.Rule.RULE_ID + entity.getId());
        }
        return b;
    }

    /**
     * 根据id获取
     * @param id
     * @return
     */
    @GetRedisCache( type = RedisKeyConstant.Rule.RULE_ID,
            value = RedisKeyConstant.REDIS_SELF)
    public TsCodeRulesEntity getById( Long id) {
        return super.getById(id);
    }

    /**
     * 查询列表
     * @param listQuery
     * @return
     */
    public  List<TsCodeRulesEntity> listCodeRules(CodeRulesListQuery listQuery) {
        QueryWrapper<TsCodeRulesEntity> query = new QueryWrapper<>();
        query.lambda().eq(StrUtil.isNotBlank(listQuery.getCode()),TsCodeRulesEntity::getCode,listQuery.getCode())
                .eq(StrUtil.isNotBlank(listQuery.getName()),TsCodeRulesEntity::getName,listQuery.getName())
                .eq(ObjUtil.isNotEmpty(listQuery.getType()),TsCodeRulesEntity::getType,listQuery.getType());
        return list(query);
    }
}
